package com.kaishengit.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.kaishengit.entity.Order;
import com.kaishengit.util.DBHelp;
 public class OrderDao {
	private DBHelp<Order> db=new DBHelp<Order>();
	
	public void save(Order order){
		String sql="Insert into t_order(id,address,tel,name,createtime,state,userid)values(?,?,?,?,?,?,?)";
		db.executeSQL(sql, order.getId(),order.getAddress(),order.getTel(),order.getName(),order.getCreatetime(),order.getState(),order.getUserid());
	}
	public List<Map<String,Object>> findByUserId(int userId){
		String sql="select id,createtime,state,(select sum(total) from t_orderitem where orderid=t_order.id) as total from t_order where userid=?";
		Connection conn=db.getConnection();
		PreparedStatement stat=null;
		ResultSet rs=null;
		List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		
		try{
			stat=conn.prepareStatement(sql);
			stat.setInt(1,userId);
			rs=stat.executeQuery();
			while(rs.next()){
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("id",rs.getString("id"));
				map.put("createtime",rs.getString("createtime"));
				map.put("state",rs.getString("state"));
				map.put("total",rs.getFloat("total"));
				list.add(map);
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			db.close(rs,stat,conn);
		}
			return list;
	}
}
